package com.jp.knowledge.activity;

import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.comm.InfoDetailData;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.InfoTopicDetailAdapter;
import com.jp.knowledge.dialog.InfoDetailCommentDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.InfoData;
import com.jp.knowledge.model.ReplyListModel;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.TimeUtil;
import com.jp.knowledge.view.TalkBottomBarReplyView;
import com.jp.knowledge.view.TalkBottomBarView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/1/14.
 */

public class InfoTopicDetailActivity extends SlidingActivity implements View.OnClickListener,
        CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener,
        ResultSubscriber.OnResultListener, RecycleVAdapter.OnItemClickListener, TalkBottomBarReplyView.ReplyBottomBarCallback {

    public static final String COMMENT_POSITION = "commentPosition";

    private static final int REFRESH_LIST_CODE = 0x01;
    private static final int LOAD_MODE_LIST_CODE = 0x02;
    private static final int DELETE_REPLY = 0x03;

    private InfoDetailData infoDetailData;
    private int commentPosition;
    private TopicListInfo topicInfo;
    private InfoTopicDetailAdapter adapter;
    private List<ReplyListModel> replyList;

    @ViewInject(R.id.reply_head)
    private ImageView replyHead;
    @ViewInject(R.id.reply_num_text)
    private TextView replyNum;
    @ViewInject(R.id.reply_name)
    private TextView replyName;
    @ViewInject(R.id.reply_time)
    private TextView replyTime;
    @ViewInject(R.id.reply_content)
    private TextView replyContent;
    @ViewInject(R.id.reply_praise_num)
    private TextView replyPraiseNum;
    @ViewInject(R.id.reply_reward_num)
    private TextView replyPayRewardNum;
    @ViewInject(R.id.reply_delete)
    private TextView replyelete;

    @ViewInject(R.id.reply_all_view)
    private LinearLayout replyAllView;
    @ViewInject(R.id.reply_all_remind)
    private TextView replyAllRemind;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout replyRefreshView;
    @ViewInject(R.id.can_content_view)
    private RecyclerView replyAllRv;
    @ViewInject(R.id.reply_bottom_talk_bar)
    private TalkBottomBarReplyView replyBottomTalkBar;

    private InfoDetailCommentDialog commentDialog;
    private InfoData infoData;

    @Override
    protected int getResourceId() {
        return R.layout.activity_info_topic_detail;
    }

    @Override
    protected void init() {
        infoDetailData = InfoDetailData.getInfoDetail();
        commentPosition = getIntent().getIntExtra(COMMENT_POSITION, -1);
        infoData = infoDetailData.getInfoData();
        if(commentPosition >= 0)
            topicInfo = infoDetailData.getTopicList().get(commentPosition);
        if(topicInfo == null)
            topicInfo = new TopicListInfo();
        String uuid = application.getUserData() == null ? null : application.getUserData().getUuid();
        adapter = new InfoTopicDetailAdapter(this, new ArrayList<ReplyListModel>(), uuid);
        adapter.addItemClickListener(this);

        initMainView();
        initReplyAllView();
        initDialog();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(0x22000000);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0)
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            contentView.setPadding(contentView.getPaddingLeft(),
                    contentView.getPaddingTop() + statusBarHeight,
                    contentView.getPaddingRight(),
                    contentView.getPaddingBottom());
        }
        replyRefreshView.autoRefresh();
    }

    private void initDialog(){
        replyBottomTalkBar.setTag(-1);
        commentDialog = new InfoDetailCommentDialog(mContext);
        commentDialog.setOnSendBtnClickListener(new InfoDetailCommentDialog.OnSendBtnClickListener() {
            @Override
            public void onSendClick() {
                String commentContent = commentDialog.getEditContent();
                if(commentContent.trim().length() == 0) {
                    ToasUtil.toast(mContext, "请输入有效内容后再提交");
                    return;
                }
                int replyPosition = (int) replyBottomTalkBar.getTag();
                TalkBottomBarReplyView.ReplyParamsBean replyParamsBean = addReplyParamsBean(replyPosition);
                JsonObject param = new JsonObject();
                param.addProperty("infoId", replyParamsBean.getInfoId());
                param.addProperty("topicId", replyParamsBean.getTopicId());
                param.addProperty("commentId", replyParamsBean.getCommentId());
                param.addProperty("toUid", replyParamsBean.getToUid());
                param.addProperty("toCommentId", replyParamsBean.getToCommentId());
                param.addProperty("content", commentDialog.getEditContent());
                param.addProperty("type",infoDetailData.getInfoData().getType());
                HttpHelper.getInstance(mContext).replyTopic(param, replyPosition >= 0 ? replyPosition+1 : 0, new ResultSubscriber.OnResultListener() {
                    @Override
                    public void onStart(int requestType) {
                        loading.show();
                    }
                    @Override
                    public void onCompleted(int requestType) {
                        loading.cancel();
                    }
                    @Override
                    public void onError(int requestType) {
                        onCompleted(requestType);
                    }
                    @Override
                    public void onNext(IModel data, int requestType) {
                        if(data.getErrcode() != 0){
                            ToasUtil.toast(mContext, data.getMessage());
                            onError(requestType);
                        }
                        ToasUtil.toast(mContext, "评论成功");
                        httpEventFinish(data, TalkBottomBarReplyView.COMMIT_COMMENT_CODE);
                        commentDialog.clearEditContent();
                    }
                });
                commentDialog.dismiss();
            }
        });
        replyBottomTalkBar.setOnCommentBtnClickListener(new TalkBottomBarView.OnCommentBtnClickListener() {
            @Override
            public void onCommentBtnClick(View v) {
                String toUserName = "";
                toUserName = setToUserName(-1);
                if(toUserName == null)
                    toUserName = "";
                commentDialog.setEditHint("回复" + toUserName);
                replyBottomTalkBar.setTag(-1);
                commentDialog.show();
            }
        });
    }

    private void initMainView(){
        ImageLoadUtil.loadCircle(this,
                topicInfo.getPortrait() + "?imageView2/2/w/80/interlace/1", replyHead);
        setText(replyName, topicInfo.getUserName());
        setText(replyTime, TimeUtil.friendly_time(topicInfo.getTime()));
        setText(replyContent, topicInfo.getContent());
        setText(replyPraiseNum, topicInfo.getPraiseNum() + "");
        setText(replyPayRewardNum, 0 + "");
//        UserData userData = application.getUserData();
//        if (topicInfo.getUid() != null
//                && userData != null && userData.getIsLogin() == 1
//                && topicInfo.getUid().equals(userData.getUuid())
//                && topicInfo.getReplyNum() == 0) {
//            replyelete.setVisibility(View.VISIBLE);
//        } else{
//            replyelete.setVisibility(View.GONE);
//        }

        replyRefreshView.setRefreshEnabled(true);
        replyRefreshView.setLoadMoreEnabled(true);
        replyRefreshView.setOnRefreshListener(this);
        replyRefreshView.setOnLoadMoreListener(this);
        replyAllRv.setHasFixedSize(true);
        replyAllRv.setLayoutManager(new LinearLayoutManager(this));
        replyAllRv.setAdapter(adapter);
        replyBottomTalkBar.setShadeView(findViewById(R.id.reply_shade_view));
        replyBottomTalkBar.getContentView()
                .setBackgroundColor(getResources().getColor(R.color.gray_bg));
        replyBottomTalkBar.setReplyBottomBarCallback(this);

        replyelete.setOnClickListener(this);
        findViewById(R.id.reply_return).setOnClickListener(this);
        findViewById(R.id.reply_praise_btn).setOnClickListener(this);
        findViewById(R.id.reply_reward_btn).setOnClickListener(this);
    }

    private void initReplyAllView(){
        setText(replyNum, topicInfo.getReplyNum() + "");
        if(topicInfo.getReplyNum() == 0)
            replyAllRemind.setVisibility(View.GONE);
        else
            replyAllRemind.setVisibility(View.VISIBLE);
        if(replyList == null)
            replyList = new ArrayList<>();
        adapter.updateAdapter(replyList);
    }

    private void setText(TextView textView, String str){
        if(str == null)
            textView.setText("");
        else
            textView.setText(str);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.reply_return:
                finish();
                break;
            case R.id.reply_delete:
                deleteReply();
                break;
            case R.id.reply_praise_btn:
                replyBottomTalkBar.praise();
                break;
            case R.id.reply_reward_btn:
                replyBottomTalkBar.payReward();
                break;
        }
    }

    /* 获取回复列表 */
    private void getReplyList(int mode){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("commentId", topicInfo.getCommentId());
        long time = 0;
        if (replyList != null && replyList.size() > 0) {
            if (mode == 0) {
                time = replyList.get(0).getTime();
            } else {
                time = replyList.get(replyList.size() - 1).getTime();
            }
        }
        param.addProperty("time", time);
        param.addProperty("mode", mode);
        HttpHelper.getInstance(mContext).replyList(param, (mode == 0) ? REFRESH_LIST_CODE : LOAD_MODE_LIST_CODE, this);
    }

    /* 删除话题 */
    private void deleteReply(){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", infoDetailData.getLinkId());
        param.addProperty("type", infoDetailData.getLinkType());
        HttpHelper.getInstance(this).topicDelete(param, DELETE_REPLY, this);
    }

    @Override
    public void onRefresh() {
        getReplyList(0);
    }
    @Override
    public void onLoadMore() {
        getReplyList(1);
    }

    @Override
    public void itemSelect(int position) {
//        replyBottomTalkBar.setReplyPosition(position);
//        replyBottomTalkBar.showSoftAndEdit();
        replyBottomTalkBar.setTag(position);
        String toUserName = "";
        toUserName = setToUserName(-1);
        if(toUserName == null)
            toUserName = "";
        commentDialog.setEditHint("回复" + toUserName);
        commentDialog.show();
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_LIST_CODE)
            replyRefreshView.refreshComplete();
        else if(requestType == LOAD_MODE_LIST_CODE)
            replyRefreshView.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0) {
            ToasUtil.toast(this, data.getMessage());
            onError(requestType);
            return;
        }
        if(requestType == DELETE_REPLY){
            ToasUtil.toast(this, "话题删除成功");
            infoDetailData.getTopicList().remove(commentPosition);
            infoDetailData.getTopicInfo().setDiscuss(infoDetailData.getTopicInfo().getDiscuss());
            finish();
        }
        if(requestType != REFRESH_LIST_CODE && requestType != LOAD_MODE_LIST_CODE)
            return;
        List<ReplyListModel> replyListModel = data.getList(ReplyListModel.class);
        if(replyList == null)
            replyList = new ArrayList<>();
        if(requestType == REFRESH_LIST_CODE && replyList != null){
            replyList = replyListModel;
        } else if(requestType == LOAD_MODE_LIST_CODE && replyList != null){
            replyList.addAll(replyListModel);
        }
        initReplyAllView();
    }

    /**
     * 以下函数用于与底部栏交互
     */
    /* 添加点赞所需要的参数 */
    @Override
    public TalkBottomBarReplyView.PraiseParamsBean addPraiseParamsBean() {
        TalkBottomBarReplyView.PraiseParamsBean paramsBean = new TalkBottomBarReplyView.PraiseParamsBean();
        paramsBean.setTopicId(infoDetailData.getTopicInfo().getTopicId());
        paramsBean.setCommentId(topicInfo.getCommentId());
        paramsBean.setInfoId(infoDetailData.getLinkId());
        return paramsBean;
    }
    /* 添加回复所需要的参数 */
    @Override
    public TalkBottomBarReplyView.ReplyParamsBean addReplyParamsBean(int replyPosition) {
        TalkBottomBarReplyView.ReplyParamsBean replyParamsBean = new TalkBottomBarReplyView.ReplyParamsBean();
        replyParamsBean.setInfoId(infoDetailData.getLinkId());
        replyParamsBean.setCommentId(topicInfo.getCommentId());
        replyParamsBean.setTopicId(infoDetailData.getTopicInfo().getTopicId());
        try {
            replyParamsBean.setToCommentId(replyList.get(replyPosition).getCommentId());
            replyParamsBean.setToUid(replyList.get(replyPosition).getUid());
        } catch (Exception e){
//            replyParamsBean.setToCommentId(topicInfo.getCommentId());
            replyParamsBean.setToCommentId(null);
            replyParamsBean.setToUid(topicInfo.getUid());
        }
        return replyParamsBean;
    }
    /* 设置要回复用户的用户名 */
    @Override
    public String setToUserName(int replyPosition) {
        String toUserName = "";
        try{
            toUserName = replyList.get(replyPosition).getUserName();
        } catch (Exception e){
            toUserName = topicInfo.getUserName();
        }
        return toUserName;
    }
    /* 设置是否已经点过赞了 */
    @Override
    public int setIsPraise() {
        return topicInfo.getIsPraise();
    }
    /* 设置点赞数 */
    @Override
    public int setPraiseNum() {
        return topicInfo.getPraiseNum();
    }
    /* 底部栏成功从服务器获取数据后的回调 */
    @Override
    public void httpEventFinish(IModel data, int requestCode) {
        if(requestCode  == TalkBottomBarReplyView.PRAISE_CODE){
            topicInfo.setIsPraise(1);
            topicInfo.setPraiseNum(topicInfo.getPraiseNum()+1);
            setText(replyPraiseNum, topicInfo.getPraiseNum() + "");
        } else if(requestCode%10 == TalkBottomBarReplyView.COMMIT_COMMENT_CODE){
            ReplyListModel replyModel = data.getEntity(ReplyListModel.class);
            replyModel.setReplyData(replyModel.getReply());
            if(requestCode != TalkBottomBarReplyView.COMMIT_COMMENT_CODE){
                ReplyListModel toReplyModel = replyList.get(requestCode / 10);
                ReplyListModel.ReplyDataBean replyData = new ReplyListModel.ReplyDataBean();
                replyData.setContent(toReplyModel.getContent());
                replyData.setUid(toReplyModel.getUid());
                replyData.setUserName(toReplyModel.getUserName());
                replyModel.setReplyData(replyData);
            }
            replyList.add(0, replyModel);
            TopicListInfo.ReplyDataBean replyDataBean = null;
            if(topicInfo.getReplyNum() == 0 || topicInfo.getReplyData() == null){
                replyDataBean = new TopicListInfo.ReplyDataBean();
                topicInfo.setReplyData(replyDataBean);
            } else{
                replyDataBean = topicInfo.getReplyData();
            }
            replyDataBean.setContent(replyModel.getContent());
            replyDataBean.setUid(replyModel.getUid());
            replyDataBean.setUserName(replyModel.getUserName());
            topicInfo.setReplyNum(topicInfo.getReplyNum()+1);
            initReplyAllView();
            replyAllRv.smoothScrollToPosition(0);
        }
    }
}
